package com.micda.moroccoby.common.dao;

import java.io.Serializable;
import java.util.*;
import java.util.Map.*;

import javax.persistence.*;

public abstract class GenericDAO<T, PK> implements Serializable {

    private Class<T> entityClass;

    public GenericDAO(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    protected abstract EntityManager getEntityManager();

    public void create(T entity) {
        getEntityManager().persist(entity);
    }

    public void save(T entity) {
        getEntityManager().merge(entity);
    }

    public void delete(T entity) {
        getEntityManager().remove(getEntityManager().merge(entity));
    }

    public T find(PK id) {
        return getEntityManager().find(entityClass, id);
    }
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public List<T> findAll() {
        Query q = getEntityManager().createQuery("select t from " + entityClass.getName() + " t");
        return q.getResultList();
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public List<T> findRange(int[] range) {
        Query q = getEntityManager().createQuery("select t from " + entityClass.getName() + " t");
        q.setMaxResults(range[1] - range[0]);
        q.setFirstResult(range[0]);
        return q.getResultList();
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public int count() {
        Query q = getEntityManager().createQuery("select count(t) from " + entityClass.getName() + " t"); 
        return ((Long) q.getSingleResult()).intValue();
    }
}
